#!/usr/bin/env python3

import sys, os
import yaml
logConfigTemplateFile = "./template/logconfig-template.yaml"
logConfigYamlDir = "."

def appConf(appconf):
    """获取应用配置,并结构化"""
    with open(appconf, 'r', encoding='utf-8') as f:
        app_conf = f.read()
        app_conf = yaml.load(app_conf, Loader=yaml.FullLoader)
    return app_conf

with open(logConfigTemplateFile, 'r') as f:
    logConfigTmp = f.read()

if __name__ == "__main__":
    args = sys.argv
    appName, namespace, appconf = args[1:]
    #appName = "abc"
    #namespace = "test"

    if namespace == "pro":
        logsetName = "k8s-ai-生产"
        logsetId = "d0d5a28f-d08a-4297-8093-a822f25b5d27"
    else:
        logsetName = "k8s-app-非生产"
        logsetId = "e21623bb-ff2c-49ec-9f19-63311bc8064d"
    
    logconf = appConf(appconf)
    # print(logconf)
    applog = logconf['containerLog']['applog'][0]['logPath']
    # print(applog)
    logFilePath  = "/".join(applog.split("/")[:-1])
    fileName = applog.split("/")[-1]
    # print(logFilePath, fileName)

    # 判断是否开启event
    # if "eventlog" in logconf['containerLog']:
    #     eventlog = logconf['containerLog']['eventlog'][0]['logPath']
    #     print(eventlog)
    #     logFilePath  = "/".join(eventlog.split("/")[:-1])
    #     fileName = eventlog.split("/")[-1]
    #     print(logFilePath, fileName)

    logConfigYaml = logConfigTmp.format(appName=appName, namespace=namespace, logsetName=logsetName, logsetId=logsetId, logFilePath=logFilePath, fileName=fileName)
    
    logConfigYamlFilePath = "%s/%s" % (logConfigYamlDir, namespace)
    if not os.path.exists(logConfigYamlFilePath): os.mkdir(logConfigYamlFilePath)

    logConfigYamlFile = "%s/log-config-%s.yaml" % (logConfigYamlFilePath, appName)
    with open(logConfigYamlFile, 'w') as f:
        f.write(logConfigYaml)

    print(logConfigYamlFile)